import 'package:flutter/material.dart';
import 'package:ideology/features/screens/widgets/editor_menu_bar/setting/utils/list_lib_sub_folders.dart';
import 'package:path/path.dart' as p;

/// 一个用于展示和管理 SDK 库路径的完整页面 Tab。
///
/// - [installed] 已安装或添加的 SDK 路径列表。
/// - [current] 当前正在使用的 SDK 路径。
/// - [onMakeCurrent] 将某个 SDK 设为当前 SDK 的回调。
/// - [onRemove] 移除某个 SDK 的回调。
/// - [onRevealInFinder] 在文件浏览器中打开某个路径的回调。
class LibrariesTabFull extends StatefulWidget {
  const LibrariesTabFull({
    super.key,
    required this.installed,
    required this.current,
    required this.onMakeCurrent,
    required this.onRemove,
    required this.onRevealInFinder,
  });

  final List<String> installed;
  final String? current;
  final ValueChanged<String> onMakeCurrent;
  final ValueChanged<String> onRemove;
  final Future<void> Function(String) onRevealInFinder;

  @override
  State<LibrariesTabFull> createState() => _LibrariesTabFullState();
}

class _LibrariesTabFullState extends State<LibrariesTabFull> {
  final _scrollCtrl = ScrollController();

  @override
  void dispose() {
    _scrollCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final cs = theme.colorScheme;

    // 如果没有安装任何 SDK，则展示空状态
    if (widget.installed.isEmpty) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.folder_open_outlined,
              size: 58,
              color: cs.onSurfaceVariant,
            ),
            const SizedBox(height: 8),
            Text(
              'No SDKs installed or added',
              style: theme.textTheme.titleMedium,
            ),
            const SizedBox(height: 6),
            Text(
              'Download from another tab, or add a local SDK path.',
              textAlign: TextAlign.center,
              style: theme.textTheme.bodyMedium?.copyWith(
                color: cs.onSurfaceVariant,
              ),
            ),
          ],
        ),
      );
    }

    // 有 SDK 时，展示列表
    return Scrollbar(
      controller: _scrollCtrl,
      thumbVisibility: true,
      child: ListView.builder(
        controller: _scrollCtrl,
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        itemCount: widget.installed.length,
        itemBuilder: (context, idx) {
          final sdkPath = widget.installed[idx];
          final isCurrent = widget.current != null && sdkPath == widget.current;

          return FutureBuilder<List<String>>(
            future: listLibSubfolders(sdkPath),
            builder: (context, snap) {
              final hasError = snap.hasError;
              final subdirs = snap.data ?? const <String>[];

              return Padding(
                padding: const EdgeInsets.only(bottom: 16),
                child: _SdkCard(
                  isCurrent: isCurrent,
                  sdkPath: sdkPath,
                  subdirs: subdirs,
                  hasError: hasError,
                  onMakeCurrent: widget.onMakeCurrent,
                  onRemove: widget.onRemove,
                  onRevealInFinder: widget.onRevealInFinder,
                ),
              );
            },
          );
        },
      ),
    );
  }
}

/// SDK 卡片，用于展示单个 SDK 信息（路径、子目录、状态等）。
///
/// - 支持显示当前 SDK 的高亮样式。
/// - 支持展示 lib/ 下的子目录 chip。
/// - 支持错误状态提示。
class _SdkCard extends StatelessWidget {
  const _SdkCard({
    required this.isCurrent,
    required this.sdkPath,
    required this.subdirs,
    required this.hasError,
    required this.onMakeCurrent,
    required this.onRemove,
    required this.onRevealInFinder,
  });

  final bool isCurrent;
  final String sdkPath;
  final List<String> subdirs;
  final bool hasError;
  final ValueChanged<String> onMakeCurrent;
  final ValueChanged<String> onRemove;
  final Future<void> Function(String) onRevealInFinder;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final cs = theme.colorScheme;

    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      curve: Curves.easeOut,
      decoration: BoxDecoration(
        color: cs.surface,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(
          color: isCurrent
              ? cs.primary.withOpacity(0.6)
              : cs.outlineVariant.withOpacity(0.4),
          width: isCurrent ? 1.5 : 1,
        ),
        boxShadow: [
          if (isCurrent)
            BoxShadow(
              color: cs.primary.withOpacity(0.08),
              blurRadius: 16,
              offset: const Offset(0, 6),
            ),
        ],
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(14),
        onTap: () {}, // 预留：未来可能支持展开/收起操作
        child: Padding(
          padding: const EdgeInsets.fromLTRB(14, 12, 12, 12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 顶部：图标 + 标题 + 当前标签
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: cs.primaryContainer,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Icon(
                      Icons.widgets_outlined,
                      color: cs.onPrimaryContainer,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: _TitleAndPath(
                      sdkPath: sdkPath,
                      isCurrent: isCurrent,
                    ),
                  ),
                  const SizedBox(width: 8),
                ],
              ),

              const SizedBox(height: 10),

              // 内容区域：错误提示 或 子目录 chips
              if (hasError)
                Row(
                  children: [
                    Icon(Icons.error_outline, color: cs.error),
                    const SizedBox(width: 6),
                    Text(
                      'Failed to read lib/ subdirectories',
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: cs.error,
                      ),
                    ),
                  ],
                )
              else
                _SubdirChips(
                  sdkPath: sdkPath,
                  subdirs: subdirs,
                  onRevealInFinder: onRevealInFinder,
                ),
            ],
          ),
        ),
      ),
    );
  }
}

/// 展示 SDK 的标题（目录名）和路径信息。
///
/// - 标题为目录 basename。
/// - 如果是当前 SDK，则在右侧显示 `Current` 标签。
class _TitleAndPath extends StatelessWidget {
  const _TitleAndPath({required this.sdkPath, required this.isCurrent});

  final String sdkPath;
  final bool isCurrent;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final cs = theme.colorScheme;

    final name = _basename(sdkPath);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Wrap(
          spacing: 8,
          crossAxisAlignment: WrapCrossAlignment.center,
          children: [
            Text(
              name,
              style: theme.textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.w600,
                color: theme.colorScheme.onSurface,
              ),
            ),
            if (isCurrent)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                decoration: BoxDecoration(
                  color: cs.primary.withOpacity(0.12),
                  borderRadius: BorderRadius.circular(999),
                  border: Border.all(color: cs.primary.withOpacity(0.3)),
                ),
                child: Text(
                  'Current',
                  style: theme.textTheme.labelSmall?.copyWith(
                    color: cs.primary,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
          ],
        ),
        const SizedBox(height: 2),
        Text(
          sdkPath,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: theme.textTheme.bodySmall?.copyWith(
            color: cs.onSurfaceVariant,
          ),
        ),
      ],
    );
  }
}

/// 展示 SDK 的 lib/ 下的子目录 chips。
///
/// - 如果没有子目录，则提示 "No subfolders under lib/"。
/// - 点击某个 chip 会调用 [onRevealInFinder] 打开对应路径。
class _SubdirChips extends StatelessWidget {
  const _SubdirChips({
    required this.sdkPath,
    required this.subdirs,
    required this.onRevealInFinder,
  });

  final String sdkPath;
  final List<String> subdirs;
  final Future<void> Function(String) onRevealInFinder;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final cs = theme.colorScheme;

    if (subdirs.isEmpty) {
      return Text(
        'No subfolders under lib/',
        style: theme.textTheme.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
      );
    }

    return Wrap(
      spacing: 8,
      runSpacing: 8,
      children: subdirs.map((name) {
        final subPath = p.join(sdkPath, 'lib', name);
        return ActionChip(
          label: Text(name),
          avatar: const Icon(Icons.storage, size: 18),
          onPressed: () => onRevealInFinder(subPath),
          tooltip: 'Open $name',
          side: const BorderSide(color: Color(0xFFBDBDBD)),
          backgroundColor: cs.surfaceContainerHighest,
          labelStyle: theme.textTheme.bodyMedium?.copyWith(
            decoration: TextDecoration.none,
            color: cs.onSurface,
          ),
        );
      }).toList(),
    );
  }
}

/// 获取路径的最后一级目录名（兼容 Windows 与 Unix）。
String _basename(String path) {
  final parts = path.replaceAll('\\', '/').split('/');
  return parts.isEmpty
      ? path
      : parts.lastWhere((e) => e.isNotEmpty, orElse: () => path);
}
